package top.mybatisx.sql.core.sql;

import top.mybatisx.sql.core.sql.base.BaseSql;
import top.mybatisx.sql.core.sql.brige.WhereJoin;
import top.mybatisx.sql.core.table.TableDef;
import top.mybatisx.sql.core.toolkit.ChkUtil;

/**
 * 查询
 */
public interface From<T extends WhereJoin> extends BaseSql {

    StringBuilder fromSql = new StringBuilder();

    default T from(Class<? extends TableDef> fromTableClass) {
        return this.from(fromTableClass, null);
    }

    default T from(Class<? extends TableDef> fromTableClass, String alias) {
        TableDef tableDef = null;
        try {
            tableDef = fromTableClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        tableDef.setAlias(alias);
        tableAliasMap.put(tableDef.getTableName(), alias);

        this.fromTable.add(tableDef);
        return (T) this;
    }

    default T from(String tableName) {
        fromSql.append(" from " + tableName + " ");
        return (T) this;
    }

    default String buildFromSql() {
        if (fromSql.length() > 0 || fromTable.size() == 0) {
            // 如果手工设置了 sql, 直接返回
            return fromSql.toString();
        }
        fromSql.setLength(0);
        fromSql.append(" from ");

        for (TableDef tableDef : fromTable) {
            String sql = tableDef.getTableName() + " ";
            String alias = tableAliasMap.get(tableDef.getTableName());
            if (ChkUtil.isNotNull(alias)) {
                sql += " as " + alias + ",";
            }
            fromSql.append(sql);
        }
        // 去掉 列 最后的逗号
        fromSql.deleteCharAt(fromSql.length() - 1);
        fromSql.append(' ');

        return fromSql.toString();
    }

}
